package org.example.mall4j.pojo;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class SysUser implements Serializable,UserDetails {
    @Serial
    private static final long serialVersionUID = 1L;
    @TableId
    private String sid;
    private String userNo;
    private String userName;
    private String password;
    private String nickName;
    private String phoneNumber;
    private String email;
    private String role;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        String[] roles = role.split(",");
        //取出所有的权限，并且给每个权限都要进行认证，添加到 SimpleGrantedAuthority()
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        //遍历roles，取出每一个权限，添加到 简单的授予认证类
        for (String s : roles) {
            //添加了 ROLE_ 前缀 为了前端页面thymeleaf-security 中自带的 hasRole()方法，能得到ROLE_格式的角色信息
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+s));
        }
        //返回到已经被 授予认证的权限集合 这里面的角色所拥有的权限都已经被spring security所知道
        return simpleGrantedAuthorities;
    }

    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
